package com.grandtech.insurance.common.utils.trans;

import com.grandtech.insurance.common.db.jdbc.sql.ReflectUtil;
import com.grandtech.insurance.common.db.jdbc.sql.TransferUtil;

import java.util.ArrayList;
import java.util.List;

public final class ListUtil {
    private ListUtil() {
    }

    public static <T> String classField2SqlWhereIn(List<T> list, String fieldName) {
        if (list == null || list.size() == 0) return null;
        StringBuffer whereInBuffer = new StringBuffer();
        whereInBuffer.append(fieldName).append(" in ( ");
        T t;
        Class<?> type = null;
        Object val;
        String item;
        for (int i = 0; i < list.size(); i++) {
            t = list.get(i);
            if (type == null) type = ReflectUtil.getFieldTypeByName(t.getClass(), fieldName);
            val = ReflectUtil.getFieldValue(t, fieldName);
            item = TransferUtil.objectToInWhere(type, val);
            whereInBuffer.append(item);
        }
        if (whereInBuffer != null && whereInBuffer.toString().endsWith(",")) {
            whereInBuffer.delete(whereInBuffer.toString().lastIndexOf(","), whereInBuffer.toString().length());
        }
        whereInBuffer.append(" )");
        return whereInBuffer.toString();
    }

    public static <T> List<String> classField2ListStr(List<T> list, String fieldName) {
        if (list == null || list.size() == 0) return null;
        T t;
        Class<?> type = null;
        String item;
        List<String> res = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            t = list.get(i);
            if (type == null) type = ReflectUtil.getFieldTypeByName(t.getClass(), fieldName);
            item = ReflectUtil.getFieldValueT(t, fieldName);
            res.add(item);
        }
        return res;
    }

    public static <T> T getLastItemT(List<T> list) {
        if (list == null) return null;
        int len = list.size();
        if (len == 0) return null;
        return list.get(len - 1);
    }

    public static <T> List<T> pageList(List<T> list, int start, int end) {
        if (list == null) return null;
        int len = list.size();
        if (start > len) return null;
        if (end > len) return list.subList(start, len);
        return list.subList(start, end);
    }
}
